<?php
namespace Common\Model;
use Think\Model;

/**
 * Class GateModel
 * @package Common\Model
 * 河道闸门表
 */
class GateModel extends BaseModel{
    public $pix = "";
    public $fieldsStr = '*';
    public $orderStr = 'gate_name asc';

    public function field_array(){
        /**
         * type:
         * 1，文本框
         * 2，下拉框
         * 3，数值查询，带条件
         * 4，日期查询，带条件
         */
        $array = array(
            'base' => array(
                'text' => '基本信息',
                'children'=>array(
                    array('field'=>'ps_id','text' => '','type'=>0),
                    array('field'=>'gate_number','text' => '闸门编号','type'=>1),
                    array('field'=>'gate_name','text' => '闸门名称','type'=>1),
                    array('field'=>'gate_mrf','text' => '生产厂家','type'=>1),
                    array('field'=>'gate_model','text' => '型号','type'=>1),
                    array('field'=>'mobile','text' => '执勤电话','type'=>1),
                    array('field'=>'gate_motorpower','text' => '电机功率(千瓦)','type'=>3,'condition'=>get_condition_array()),
                    array('field'=>'gate_blev','text' => '闸门高程(米)','type'=>3,'condition'=>get_condition_array()),
                    array('field'=>'gate_h','text' => '闸门高(米)','type'=>3,'condition'=>get_condition_array()),
                    array('field'=>'gate_wid','text' => '闸门宽(米)','type'=>3,'condition'=>get_condition_array()),
                    array('field'=>'gate_svcdt','text' => '投运日期','type'=>4,'condition'=>get_condition_array()),
                    array('field'=>'gate_ctltype','text' => '闸门类型','type'=>2, 'option_text'=>gate_cont_type_option()),
                    array('field'=>'gate_switsty','text' => '闸门类型','type'=>2, 'option_text'=>gate_swit_sty_option()),
                ),
            ),
        );
        return $array;
    }

    public function get_list_use_page($map=array(), $cur_page, $rows_num){
        $map_filter = filter_query_map_get_order_str($map, $this->orderStr);
        $map = $map_filter['map'];
        $order_str = $map_filter['order_str'];
        $map = filter_field_array($this->field_array(), $map);
        $count = M('Gate')->where($map)->count();
        $list = $this->where($map)->order($order_str)->page($cur_page.",$rows_num")->select();
        $gate_model = D('Gate');
        $temp_status = 0;
        foreach($list as $k => $v){
            $list[$k]['opr_temp'] = filter_id_to_ralname($list[$k]['gate_opr']);
            $list[$k]['gate_ctltype'] = gate_cont_type_option($list[$k]['gate_ctltype'], false);
            $list[$k]['charge_person'] = filter_id_to_ralname($list[$k]['gate_opr']);
            $list[$k]['gate_switsty'] = gate_swit_sty_option($list[$k]['gate_switsty'], false);
            $gate_status = $gate_model->q_s($v['id']);
            if($gate_status==-1){
                $temp_status = -2;
            }else if($gate_status==1){
                $temp_status = 1;
            }else{
                $temp_status = 0;
            }
            $list[$k]['status'] = station_status_option($temp_status, false);
            $temp_status = 0;
        }
        $footer = array(array('status'=>'闸门总数', 'gate_ctltype'=>$count));
        return array('total'=>$count, 'list'=>$list, 'footer'=>$footer);
    }

    public function gen_search($map, $page, $rows_num){
        $station_model = D('Gate');
        $record_model = D('GateRecord');
        $station_ids = null;
        $status = '';
        if(isset($map['id'])){
            $station_ids = my_array_filter_to_text(str_replace('%', '', $map['id'][1]), ',');
            unset($map['id']);
        }
        if(isset($map['status'])){
            $status = str_replace('%', '', $map['status'][1]);
            unset($map['status']);
        }
        if($station_ids){
            $stations = $station_model->order('gate_name desc,mobile desc')->select($station_ids);
        }else{
            $stations = $station_model->order('gate_name desc,mobile desc')->select();
        }
        $fys = $stations;
        //查询出所有设备
        $result = array();
        $all_fys = array();
        $error_list = array();
        foreach($fys as $k => $fy){
            $fy_status =  $record_model->get_last_one($fy['id']);
            if($fy_status == 999 || $fy_status == -1)
                $fy_status = 0;
            if($status == '' || $fy_status == $status){
                $fys[$k]['status'] = $fy_status;
                if($fy_status == -2)
                    $error_list[] = $fy;
                else
                    $all_fys[] = $fy;
            }
        }
        $result = array_merge($error_list, $all_fys);
        $all_fys = array_slice($result, ($page-1)*$rows_num, $rows_num);
        foreach($all_fys as $k => $fy){
            $last_record = $record_model->get_last_one_record($fy['id']);
            $fy_status =  $last_record['status'];
            if($fy_status == 999 || $fy_status == -1 || $fy_status == null)
                $fy_status = 0;
            if($status == '' || $fy_status == $status){
                $sta_temp = $fy;
                $all_fys[$k]['sta_name'] = $sta_temp['gate_name'];
                $all_fys[$k]['sta_id'] = $sta_temp['id'];
                $all_fys[$k]['work_person'] = D('MobileAdmin')->get_working_names_by_ids($sta_temp['gate_opr']);
                $all_fys[$k]['status_text'] = gate_status_option($fy_status, false);
                if($fy_status==0){
                    $time = strtotime($last_record['gate_off'])-strtotime($last_record['gate_start']);
                    $all_fys[$k]['work_time'] = round(timestamp_to_time('hour', $time), 2);
                }else if($fy_status==1){
                    $time = strtotime(getNowTime())-strtotime($last_record['gate_start']);
                    $all_fys[$k]['work_time'] = round(timestamp_to_time('hour', $time), 2);
                }else if($fy_status < 0){
                    $all_fys[$k]['error_time'] = $last_record['date'];
                }
                $all_fys[$k]['status'] = station_status_option($fy_status, false);
                $all_fys[$k]['gate_ctltype'] = gate_cont_type_option($all_fys[$k]['gate_ctltype'], false);
                $all_fys[$k]['gate_switsty'] = gate_swit_sty_option($all_fys[$k]['gate_switsty'], false);
                $all_fys[$k]['gate_start'] = $last_record['gate_start'];
                $all_fys[$k]['gate_off'] = $last_record['gate_off'];
                $list[$k]['charge_person'] = filter_id_to_ralname($list[$k]['gate_opr']);
                $all_fys[$k]['work_log'] = '<a href="#" onclick="open_easyui_window_with_id(\'log_window\', \''.$sta_temp['gate_name'].'\', \'/Manage/AdminGate/just_see?fy_id='.$fy['id'].'\')">查看</a>';
            }
        }
        $footer = array(array('status_text'=>'闸门总数', 'gate_start'=>count($result)));
        return array('total'=>count($result), 'rows'=>$all_fys, 'footer'=>$footer);
    }

    public function filter_all(){
        $list = $this->getAll();
        foreach($list as $k => $v){
            $list[$k]['gate_opr'] = filter_id_to_ralname($list[$k]['gate_opr']);
        }
        return $list;
    }

    public function query_ids_by_opr($query_str){
        $map['gate_opr'] = array('like', '%'.$query_str.'%');
        $list = $this->where($map)->order($this->orderStr)->select();
        $push = array();
        foreach($list as $k => $v){
            $push[] = $v['id'];
        }
        return $push;
    }

    public function query_by_pids($pids){
        $log_model = D('GateRecord');
        $temp = array();
        foreach($pids as $pid){
            $map['id'] = array('eq', $pid);
            $one = $this->where($map)->find();
            $one['model'] = $this->getModelName();
            $one['statuss'] = filter_device_status($log_model->get_last_one($pid));
            $one['status'] = $log_model->get_last_one($pid);
            $temp[] = $one;
            unset($one);
        }
        return $temp;
    }

    public function get_json_obj($id){
        $art = array(
            'station' => 'Gate',
            'log' => 'GateRecord',
            'pid_field' => 'gateid',
            'sta_name_field' => 'gate_name',
        );
        $station_model = D($art['station']);
        $log_model = D($art['log']);
        $obj = $this->queryObj($id, 'id');
        $station = $station_model->queryObj($obj[$art['pid_field']], 'id');
        $obj['station'] = $station[$art['sta_name_field']];
        $obj['statuss'] = filter_device_status($log_model->get_last_one($obj['id']));
        $obj['status'] = $log_model->get_last_one($obj['id']);
        return json_encode($obj);
    }

    /**
     * @param $pid
     * 暴露的统一接口
     */
    public function count($start_time, $end_time){
        $list = $this->getAll();
        $return_array = array();
        $index = 0;
        foreach($list as $v){
            $temp = $this->calculat_record($v, $start_time, $end_time);
            $return_array[$index]['date'] = substr($start_time,0,10).'/'.substr($end_time,0,10);
            $return_array[$index]['name'] = $v['gate_name'];
            $return_array[$index]['number'] = $v['gate_number'];
            $return_array[$index]['time'] = round($temp['time'], 1);
            $return_array[$index]['res'] = $temp['res'];
            $index++;
        }
        return $return_array;
    }

    /**
     * @param $pid
     * 计算记录所需要的值
     */
    private function calculat_record($pump, $start_time, $end_time){
        $record_model = D('GateRecord');
        $map['gateid'] = array('eq', $pump['id']);
        $str = ' date>=\''.$start_time.'\' and date<=\''.$end_time.'\'';
        $list = array_reverse($record_model->query_array_str($map, $str));
        //检查第一条是否是打开记录，或者是关闭
        if($list[0]['status']){
            $start_index = 0;
        }else{
            $start_index = 1;
        }
        //运行总时间
        $time = 0;
        $temp_start_time = '';
        $temp_end_time = '';
        $temp_res = '';
        for($i=$start_index;$i<count($list);$i++){

            $record = $list[$i];
            //如果记录不是打开状态，就跳到下一条
            if($record['status'] != 1){
                continue;
            }
            if($record['status'] == 1){
                //打开
                $temp_res .= $record['gate_startreason'];
                $temp_start_time = $record['gate_start'];
                //获取下一条记录
                if(($i+1) < count($list)){
                    $next_record = $list[$i+1];
                    $temp_end_time = $next_record['gate_off'];
                    $time += strtotime($temp_end_time) - strtotime($temp_start_time);

                }else{
                    $time += strtotime($end_time) - strtotime($temp_start_time);
                }

            }else if($record['status'] == 0){
                //关闭
            }else if($record['status'] == -1){
                //维修
            }else if($record['status'] == -2){
                //故障
            }
            $temp_end_time = '';
            $temp_end_time = '';
        }
        $return_array = array();
        $return_array['time'] = timestamp_to_time('hour', $time);
        $return_array['res'] = $temp_res;
        return $return_array;
    }

    public function get_river_gate_tree(){
        $tree = array();
        $top = array();
        $top['id'] = '-1';
        $top['text'] = '全部河道闸门';
        $top['children'] = array();
        $stations = $this->order($this->orderStr)->select();
        foreach($stations as $sta){
            $temp_sta = array();
            $temp_sta['id'] = $sta['id'];
            $temp_sta['text'] = '<a href="#" onclick="editRivergate('.$sta['id'].')">'.$sta['gate_name'].'</a>';
            $top['children'][] = $temp_sta;
        }
        $tree[] = $top;
        return $tree;
    }

    public function q_s($pid){
        $return = -99;
        $record_model = D('GateRecord');
        $status = $record_model->get_last_one($pid);
        if($status < 0){
            $return = -1;
        }else if($status == 1){
            $return = 1;
        }
        return $return;
    }

    public function deleteArray($ids=array()){
        $return = '';
        if(!is_array($ids)){
            $ids = array_filter(explode(',', $ids));
        }
        $fys_models = array(
            'GateRecord',
        );
        foreach($ids as $id){
            foreach($fys_models as $fy_model){
                $map['gateid'] = array('eq', $id);
                D($fy_model)->where($map)->delete();
            }
            $return = $this->delete($id);
        }
        return $return;
    }

    public function get_infor_text($id){
        $one = $this->find($id);
        return array('text'=>$one['gate_name'].'，'.$one['gate_model'], 'phone'=>$one['mobile']);
    }
}